package com.hrm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hrm.interceptor.JwtInterceptor;
import com.hrm.mapper.NoticeMapper;
import com.hrm.pojo.Notice;
import com.hrm.service.NoticeService;
import com.hrm.utils.JwtUtil;
import com.hrm.utils.entity.PageResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public List<Notice> findByTitleAndContent(Integer pageNum, Integer pageSize, Notice notice) throws Exception {
        PageHelper.startPage(pageNum,pageSize);
        List<Notice> notices = noticeMapper.selectByTitleAndContent(notice);
        if(notices==null){
            throw new Exception("获取公告失败");
        }
        return notices;

    }

    //添加公告
    @Override
    public boolean addNotice(Notice notice) throws Exception {
        //先查询是否有该公告标题
        Notice notice1 = noticeMapper.selectByTitle(notice.getTitle());
        if(notice1!=null){
            throw new Exception("该公告标题已存在");
        }
        //获取token里面存储的id
        Integer id = Integer.parseInt((String) request.getSession().getAttribute("id"));
        notice.setUserId(id);

        //判断notice信息
        if (noticeMapper.insertSelective(notice)>0){
            return true;
        }
        return false;
    }

    //删除公告
    @Override
    public boolean deleteNotice(ArrayList<Integer> noticeIdList) throws Exception {
        for(Integer i:noticeIdList){
            if (noticeMapper.deleteByPrimaryKey(i)<=0){
                throw new Exception("公告删除有误");
            }
        }

        return true;
    }

    //修改公告
    @Override
    public boolean updateNotice(Notice notice) throws Exception {
        //判断notice修改信息
        if (noticeMapper.updateByPrimaryKeySelective(notice)>0){
            return true;
        }
        return false;
    }

    //公告预览
    @Override
    public Notice prviewNotice(Integer id) throws Exception {
        Notice notice = noticeMapper.selectByPrimaryKey(id);
        if(notice==null){
            throw new Exception("获取公告失败");
        }
        return notice;

    }
}
